<?php

/*
 * 管理当前会话状态
 */
class Session {

	/*
	 * 初始化当前会话，需要在所有非登录Action的最开始调用
	 * @return 返回当前用户id
	 */
	public static function init() {
		$session_id = $_GET['session_id'];
		if (isset($session_id)) {
			// 处理session
			session_id($session_id);
//			session_start();
			$type = session('type');
			switch ($type) {
				case session_type_user:
					Session::$user['id'] = session('id');
					Session::$user['customerId'] = session('customerId');
					Session::$user['loginName'] = session('loginName');
					Session::$user['registered'] = session('registered');
					Session::$user['role'] = session('role');
					Session::$user['isApiAuth'] = session('isApiAuth');
					Session::$user['agent'] = session('agent');
					Session::$user['agentId'] = session('agentId');
					Session::$user['fullName'] = session('fullName');
					break;
				case session_type_view:
					Session::$user['customerId'] = session('customerId');
					Session::$user['userName'] = session('userName');
					Session::$user['userId'] = session("userId");
					Session::$user['appopenid'] = session("appopenid");
					break;
				default:
					Log::write('not set user');
					return false;
			}
		} else {
			$customerId = $_GET['customerId'];
			$userName = $_GET['userName'];
			$uid=$_GET['uid'];
			if (isset($customerId)) {
				Session::$user['customerId'] = $customerId;
				
			} else {
				Log::write('not set session_id');
				return false;
			}
			if(isset($userName) && !empty($userName)){
				Session::$user['userName'] = $userName;
			}
			if(isset($uid)){
				Session::$user['uid'] = $uid;
			} 
		}
		
		if (!Session::isAdmin()) {
			Session::switchCustomer(Session::$user['customerId']);
		}
		return true;
	}
	
	/*
	 * 登录后调用，保存当前用户状态
	 * @return 当前session
	 */
	public static function setCurrentUser($user) {
		if (is_array($user)) {
			$user = (object)$user;
		}
		session_start();
		
// 		$_SESSION["isLoggedIn"] = true;
		
		$filePath = MOXIE_BASE_PATH ."/".$user->id . "/files";
		$FfilePath = MOXIE_BASE_PATH ."/".$user->id;
// 		$filePath = MOXIE_BASE_PATH ."\\".$user->id."_files";
		if (!file_exists($filePath)){
			$e = mkdir($FfilePath);
			if(!$e){
				Log::write($FfilePath.'== create error: '.$e);
			}
			$e = mkdir($filePath);
			if(!$e){
				Log::write($filePath.'== create error: '.$e);
			}
		} 
		
		//设置moxieManager
// 		session('isLoggedIn', true);
		session('moxiemanager.filesystem.rootpath', 'moxie/'.$user->id.'/files');
// 		session('moxiemanager.filesystem.rootpath', 'moxie/'.$user->id.'_files');
		////
		session('type', session_type_user);
		session('id', $user->id);
		session('customerId', $user->customerId);
		session('loginName', $user->loginName);
		session('registered', $user->registered);
		session('role', $user->role);
		session('isApiAuth', $user->isApiAuth);
		//添加上agent,email
		session('agent', $user->agent);
		session('agentId', $user->agentId);
		session('fullName', $user->fullName);
		session('email', $user->email);
		
		return (object)array('session_id' => session_id());
	}

	/*
	 * 退出登录,清空
	 */
	public static function clearCurrentUser(){
		session_start();
		session('type', null);
		session('id', null);
		session('customerId', null);
		session('loginName', null);
		session('registered', null);
		session('role', null);
		session('isApiAuth', null);
		session('agent', null);
		session('agentId', null);
		session('fullName', null);
		session('email', null);

		$result = session_destroy();
		return (object)array('session_clear' =>(int)$result);
	}
	
	/*
	 * 登录后调用，保存当前用户状态
	* @return 当前session
	*/
	public static function getViewSession($customerId, $userName) {
		
		session_start();
		session('type', session_type_view);
		session('customerId', $customerId);
		session('userName', $userName);

		return (object)array('session_id' => session_id());
	}
		
	/*
	 * 切换客户环境，用于管理员的特殊处理
	 */
	public static function switchCustomer($customerId) {
		if ($customerId == 0) {	
			C('DB_PREFIX', C('ORIGINAL_DB_PREFIX'));
		} else {
			C('DB_PREFIX', C('ORIGINAL_DB_PREFIX').$customerId.'_');
		}
		
		Session::$user['customerId'] = $customerId;
	}

	/*
	 * 切换到管理员
	*/
	public static function switchAdmin() {
		Session::switchCustomer(0);
	}	

    /** ---------------------------------------------- 下方是角色声明定义 ---------------------------------------------- */

    /**
     * 判断当前用户角色 - 商贩
     * @return bool
     */
    public static function isVendor() {
        if (isset(Session::$user['agent']))
            if (in_array(role_vendor, explode(',', Session::$user['agent'])))
                return true;

        return false;
    }

    /**
     * 判断当前用户是否拥有_超级管理员/平台管理员_权限
     *
     * 20170723 - 原来的注释(应该不对): 默认客户ID == 0，为整个系统的管理员,
     * @return bool
     */
	public static function isAdmin() {
		if (!isset(Session::$user['role'])) {
			return false;
		}

		return Session::$user['role'] == 'A';
	}

    /**
     * 判断当前用户是否拥有_超级管理员/平台管理员_权限
     * 这个和上这个isAdmin类似, 平台只有一个role为A, 同时这个人的agent包含了role_agent(11)
     * @return bool
     */
    public static function isAgent() {
        if (isset(Session::$user['agent'])) {
            if (in_array(role_agent, explode(',', Session::$user['agent']))) {
                return true;
            }
        }

        return false;
    }

    /**
     * 判断当前用户是否拥有_商家管理员/系统管理员_权限
     * @return bool
     */
    public static function isBusiness() {
        if (isset(Session::$user['agent'])) {
//            if (in_array(role_business, explode(',', Session::$user['agent']))) {
			if (in_array(role_business, explode(',', Session::$user['agent']))) {
				return true;
			}
        }

        return false;
    }

    /**
     * 判断当前用户是否拥有_普通编辑_权限
     * @return bool
     */
    public static function isEdit() {
        if (isset(Session::$user['agent'])) {
            if (in_array(role_edit, explode(',', Session::$user['agent']))) {
                return true;
            }
        }

        return false;
    }

    /**
     * 判断当前用户是否拥有_主编_权限
     * @return bool
     */
    public static function isEditor() {
        if (isset(Session::$user['agent'])) {
            if (in_array(role_editor, explode(',', Session::$user['agent']))) {
                return true;
            }
        }

        return false;
    }

	/**
	 * 判断当前用户是否拥有_商务_权限
	 * @return bool
	 */
	public static function isDb() {
		if (isset(Session::$user['agent'])) {
			if (in_array(role_db, explode(',', Session::$user['agent']))) {
				return true;
			}
		}
		return false;
	}
	/**
	 * 判断当前用户是否拥有_商务主管_权限
	 * @return bool
     * 2017-10-08 发现函数名写错, 废弃, 使用下方正确的
	 */
	public static function isBdManager() {
		if (isset(Session::$user['agent'])) {
			if (in_array(role_bdManager, explode(',', Session::$user['agent']))) {
				return true;
			}
		}
		return false;
	}

    /**
     * 判断当前用户是否拥有_商务主管_权限
     * @return bool
     */
    public static function isDbManager() {
        if (isset(Session::$user['agent'])) {
            if (in_array(role_bdManager, explode(',', Session::$user['agent']))) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断当前用户是否拥有_微梦想运营_权限
     * @return bool
     */
    public static function isWmxOperater() {
        if (isset(Session::$user['agent'])) {
            if (in_array(role_wmxOperate, explode(',', Session::$user['agent']))) {
                return true;
            }
        }
        return false;
    }

    /**
     * 判断当前用户是否拥有_微梦想财务_权限
     * @return bool
     */
    public static function isWmxFinance() {
        if (isset(Session::$user['agent'])) {
            if (in_array(role_wmxFinance, explode(',', Session::$user['agent']))) {
                return true;
            }
        }
        return false;
    }

	public static $user = array();

}